// pages/user/feedback/feedback.js
Page({
  data: {
    feedbackContent: '',
    contactInfo: '',
    uploadedImages: [],
    contentLength: 0,
    showQRCode: false
  },

  onLoad: function(options) {
    // 页面加载时的逻辑
  },

  // 输入反馈内容
  onInputChange: function(e) {
    const content = e.detail.value;
    this.setData({
      feedbackContent: content,
      contentLength: content.length
    });
  },

  // 输入联系方式
  onContactChange: function(e) {
    this.setData({
      contactInfo: e.detail.value
    });
  },

  // 选择图片
  chooseImage: function() {
    const that = this;
    wx.chooseMedia({
      count: 3 - that.data.uploadedImages.length,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: function(res) {
        const tempFiles = res.tempFiles;
        const newImages = tempFiles.map(file => file.tempFilePath);
        
        that.setData({
          uploadedImages: [...that.data.uploadedImages, ...newImages]
        });
      }
    });
  },

  // 预览图片
  previewImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.uploadedImages;
    
    wx.previewImage({
      current: images[index],
      urls: images
    });
  },

  // 删除图片
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.uploadedImages;
    images.splice(index, 1);
    
    this.setData({
      uploadedImages: images
    });
  },

  // 切换显示微信二维码
  toggleWechatQR: function() {
    this.setData({
      showQRCode: !this.data.showQRCode
    });
  },

  // 防止冒泡
  preventBubble: function() {
    return;
  },

  // 提交反馈
  submitFeedback: function() {
    if (!this.data.feedbackContent) {
      wx.showToast({
        title: '请输入反馈内容',
        icon: 'none'
      });
      return;
    }

    wx.showLoading({
      title: '提交中...',
    });

    // 调用全局请求方法提交反馈
    const app = getApp();
    app.request({
      url: '/api/feedback',
      method: 'POST',
      data: {
        content: this.data.feedbackContent,
        contact: this.data.contactInfo
      }
    }).then(res => {
      wx.hideLoading();
      
      if (res.statusCode === 200 && res.data.success) {
        // 提交成功
        wx.showToast({
          title: res.data.message || '提交成功',
          icon: 'success',
          duration: 2000
        });
        
        // 清空表单
        this.setData({
          feedbackContent: '',
          contactInfo: '',
          contentLength: 0
        });
        
        // 延迟返回上一页
        setTimeout(() => {
          wx.navigateBack();
        }, 2000);
      } else {
        // 提交失败
        wx.showToast({
          title: res.data.message || '提交失败，请重试',
          icon: 'none',
          duration: 2000
        });
      }
    }).catch(err => {
      wx.hideLoading();
      console.error('提交反馈失败:', err);
      wx.showToast({
        title: '网络错误，请重试',
        icon: 'none',
        duration: 2000
      });
    });
  }
});